package com.xkdx.caipiao;

import java.text.DecimalFormat;
import java.util.HashMap;
import java.util.List;

import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.xkdx.caipiao.fragment.UserInfoFragment;
import com.xkdx.caipiao.listener.OnAlertDialogOkListener;
import com.xkdx.caipiao.module.network.AbsModule;
import com.xkdx.caipiao.my.AddBankActivity;
import com.xkdx.caipiao.my.WithdrawDepositActivity;
import com.xkdx.caipiao.presistence.bank.BankItemInfo;
import com.xkdx.caipiao.presistence.bank.DelBankAction;
import com.xkdx.caipiao.presistence.bank.DelBankModule;
import com.xkdx.caipiao.presistence.bank.DelBankPresistence;
import com.xkdx.caipiao.presistence.bank.GetBundleBanksAction;
import com.xkdx.caipiao.presistence.bank.GetBundleBanksModule;
import com.xkdx.caipiao.presistence.bank.GetBundleBanksPresistence;
import com.xkdx.caipiao.presistence.identity.IdentityInfo;
import com.xkdx.caipiao.presistence.login.LoginInfo;
import com.xkdx.caipiao.presistence.tixian.TixianAction;
import com.xkdx.caipiao.presistence.tixian.TixianModule;
import com.xkdx.caipiao.presistence.tixian.TixianPresistence;
import com.xkdx.caipiao.statics.IConstants;
import com.xkdx.caipiao.util.Md5Utils;
import com.xkdx.caipiao.wiget.LineEditText;
import com.xkdx.caipiao.wiget.MyAlertDialog;

public class CashRequestActivity extends ThreadActivity implements
		OnClickListener, OnAlertDialogOkListener {

	TixianAction action;
	TixianModule module;
	TixianPresistence presistence;
	private RelativeLayout rl_addbank;
	Button btn_sumit;
	LineEditText et_input;

	GetBundleBanksAction bundleBanksAction;
	GetBundleBanksModule bunBanksModule;
	GetBundleBanksPresistence bundleBanksPresistence;

	ListView listView;
	List<BankItemInfo> list;
	ImageLoader imageLoader = ImageLoader.getInstance();
	DisplayImageOptions options;

	private TextView balance, ketiqu, real_name, identity_code;
	private IdentityInfo identityInfo;
	LoginInfo info;

	int defaultPosition = 0;
	int delPosition = 0;
	BankListAdapter adapter;
	DelBankAction delBankAction;
	DelBankModule delBankModule;
	DelBankPresistence delBankPresistence;
	HashMap<String, Boolean> states = new HashMap<String, Boolean>();// 用于记录每个图片的状态，并保证只可选一个
	String leftMoney = "";

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.cash_request_caipiao);
		options = new DisplayImageOptions.Builder().bitmapConfig(
				Bitmap.Config.RGB_565).build();
		LoginInfo info = getLoginInfo();
		float money = Float.valueOf(info.getMoney())/ 100;;
		DecimalFormat df = new DecimalFormat("#0.00");
		leftMoney = df.format(money);
		info = new LoginInfo();
		init();
		setClick();
	}

	private void setClick() {
		btn_sumit.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				if (et_input.getText().toString().equals("")) {
					toast("请输入金额");
					return;
				}

				String value = et_input.getText().toString();
				if (checkNumber(value)) {
					int number = Integer.valueOf(et_input.getText().toString()) * 100;

					if (number < 200 || number > 5000000) {
						toast("金额不能小于2元同时不能大于5万元");
						return;
					} else {
						if(list.size()>0){
						startThread(); // 设为默认值并提交
						}else{
							toast("请先绑定银行卡");
						}
					}
				} else {
					Toast.makeText(getApplicationContext(), "请输入正确的金额", 0)
							.show();
				}

			}
		});
	}

	public boolean checkNumber(String value) {
		String regex = "^\\d+(\\.\\d+)?$";
		return value.matches(regex);
	}

	@Override
	protected void onResume() {
		startGetBundleBankThread();
		super.onResume();
	}

	private void init() {
		et_input = (LineEditText) findViewById(R.id.balance_input);

		btn_sumit = (Button) findViewById(R.id.btn_submit);
		rl_addbank = (RelativeLayout) findViewById(R.id.rl_addbank);
		rl_addbank.setOnClickListener(this);
		listView = (ListView) findViewById(R.id.banklist);
		balance = (TextView) findViewById(R.id.balance);
		ketiqu = (TextView) findViewById(R.id.ketiqu);
		real_name = (TextView) findViewById(R.id.real_name);
		identity_code = (TextView) findViewById(R.id.identity_code);
	}

	public void onBackClick(View view) {
		finish();
	}

	public void showDelOnPost(HashMap<String, AbsModule> result) {

		if (dataLoadDialog.isShowing()) {
			dataLoadDialog.dismiss();
		}
		if (result.containsKey("0")) {
			if (delBankModule.isSuccess) {
				// list.remove(delPosition);
				// adapter.notifyDataSetChanged();
				startGetBundleBankThread();
				toast("解绑成功");
			} else {
				toast("解绑失败");

			}
		} else {
			toastErrorMessage(result);
		}
	}

	/**
	 * 提交并设置默认绑定的银行卡
	 * 
	 * @param result
	 */
	public void showOnCommitPost(HashMap<String, AbsModule> result) {
		if (dataLoadDialog.isShowing()) {
			dataLoadDialog.dismiss();
		}
		if (result.containsKey("0")) {

			if (module.isDefaultSuccess) {
				Log.i("zs", "默认设置成功");
			} else {
				toast(module.messageDefault);
			}

			if (module.isCommitSuccess) {
				IConstants.localUserMoney = 0;
				UserInfoFragment.isUpdate = true;
				toast("提现成功");
				Intent intent = new Intent(CashRequestActivity.this,
						WithdrawDepositActivity.class);
				startActivity(intent);
				finish();
			} else {
				toast(module.messageCommit);
			}

		} else {
			toastErrorMessage(result);
		}

	}

	@Override
	public void showOnPost(HashMap<String, AbsModule> result) {

		if (dataLoadDialog.isShowing()) {
			dataLoadDialog.dismiss();
		}
		if (result.containsKey("0")) {
			if (bunBanksModule.isSuccess) {
				setBaseInfo();
				setBankList(); // 显示绑定额银行卡列表
			}
		} else {
			toastErrorMessage(result);
		}

	}

	/**
	 * 设置基本信息
	 */
	private void setBaseInfo() {
		info = getLoginInfo();
		identityInfo = bunBanksModule.baseinfo;
		if (!(TextUtils.isEmpty(leftMoney))) {
			// float money = Float.parseFloat(info.getMoney()) / 100;
			balance.setText(leftMoney+"元");
		} else {
			balance.setText("0元");
		}

		if (!(TextUtils.isEmpty(identityInfo.getCash()))) {
			float ke = Float.parseFloat(identityInfo.getCash()) / 100;
			//float money = Float.valueOf(info.getMoney()) / 100;
			DecimalFormat df = new DecimalFormat("#0.00");
			String st = df.format(ke);
			ketiqu.setText(st + " 元");
		} else {
			ketiqu.setText("0元");
		}

		real_name.setText(identityInfo.getRealname());
		identity_code.setText(identityInfo.getIdcard());
	}

	ImageView imageview;

	private void setBankList() {
		list = bunBanksModule.info.getList();
		adapter = new BankListAdapter();
		listView.setAdapter(adapter);
		IConstants.setListViewHeightBasedOnChildren(listView);
		listView.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {

				defaultPosition = position;
				for (int i = 0; i < parent.getCount(); i++) {
					View v = parent.getChildAt(i);
					imageview = (ImageView) v.findViewById(R.id.already);

					if (position == i) {// 当前选中的Item改变背景颜色
						imageview.setVisibility(View.VISIBLE);
						// imageview
						// .setBackgroundResource(R.drawable.pay_success_im);
					} else {
						// imageview.setBackground(null);
						imageview.setVisibility(View.INVISIBLE);
					}

				}

			}
		});

	}

	/**
	 * 获取用户信息及绑定银行卡列表
	 */
	private void startGetBundleBankThread() {
		if (!(dataLoadDialog.isShowing())) {
			dataLoadDialog.show();
			dataLoadDialog.setContentView(R.layout.progressbar_caipiao);
		}
		LoginInfo info = getLoginInfo();
		String md5 = info.getId()+info.getLogintoken()+IConstants.key;
		String signcode = Md5Utils.md5(md5);
		bundleBanksAction = new GetBundleBanksAction(info.getId(),
				info.getLogintoken(),signcode);
		bunBanksModule = new GetBundleBanksModule();
		bundleBanksPresistence = new GetBundleBanksPresistence(this);
		bundleBanksPresistence.setActitons(bundleBanksAction);
		bundleBanksPresistence.setModule(bunBanksModule);
		bundleBanksPresistence.execute();
	}

	@Override
	public void startThread() {
		if (!(dataLoadDialog.isShowing())) {
			dataLoadDialog.show();
			dataLoadDialog.setContentView(R.layout.progressbar_caipiao);
		}
		info = getLoginInfo();
		String md5 = info.getId()+info.getLogintoken()+IConstants.key;
		String signcode = Md5Utils.md5(md5);
		action = new TixianAction(info.getId(), info.getLogintoken(),
				Integer.valueOf(et_input.getText().toString()) * 100 + "", list
						.get(defaultPosition).getId(),signcode);
		module = new TixianModule();
		presistence = new TixianPresistence(this);
		presistence.setActitons(action);
		presistence.setModule(module);
		presistence.execute();

	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.rl_addbank:
			Intent intent = new Intent(CashRequestActivity.this,
					AddBankActivity.class);
			startActivity(intent);
			break;
		}
	}

	class BankListAdapter extends BaseAdapter {

		@Override
		public int getCount() {
			// TODO Auto-generated method stub
			return list.size();
		}

		@Override
		public Object getItem(int position) {
			// TODO Auto-generated method stub
			return list.get(position);
		}

		@Override
		public long getItemId(int position) {
			// TODO Auto-generated method stub
			return position;
		}

		@Override
		public View getView(final int position, View convertView,
				ViewGroup parent) {
			Holder holder = null;
			if (convertView == null) {
				holder = new Holder();
				convertView = LayoutInflater.from(getApplicationContext())
						.inflate(R.layout.bank_item_caipiao, null);
				holder.im = (ImageView) convertView
						.findViewById(R.id.bank_icon);
				holder.name = (TextView) convertView
						.findViewById(R.id.bank_name);
				holder.number = (TextView) convertView
						.findViewById(R.id.bank_number);
				holder.del = (TextView) convertView
						.findViewById(R.id.set_defalt);
				holder.already = (ImageView) convertView
						.findViewById(R.id.already);

				convertView.setTag(holder);
			} else {
				holder = (Holder) convertView.getTag();
			}
			imageLoader.displayImage(list.get(position).getBankicon(),
					holder.im, options);
			Log.i("图片图片图片图片图片图片图片图片图片图片", list.get(position).getBankicon());
			holder.name.setText(list.get(position).getBankname());
			holder.number.setText("卡号:" + list.get(position).getCardid());
			if (position == 0) {
				holder.already.setVisibility(View.VISIBLE);
			}
			holder.del.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					delPosition = position;
					MyAlertDialog.creatAlertDialog(CashRequestActivity.this,
							"解绑提示", "确定解除绑定该银行卡?");
					MyAlertDialog
							.setOnAlertDialogOklistener(CashRequestActivity.this);

				}
			});

			return convertView;
		}

		class Holder {
			ImageView im, already;
			TextView name, number, del;
		}

	}

	protected void startDelBank() {
		if (!(dataLoadDialog.isShowing())) {
			dataLoadDialog.show();
			dataLoadDialog.setContentView(R.layout.progressbar_caipiao);
		}
		LoginInfo info = getLoginInfo();
		String md5 = info.getId()+info.getLogintoken()+IConstants.key;
		String signcode = Md5Utils.md5(md5);
		delBankAction = new DelBankAction(list.get(delPosition).getId(),
				info.getLogintoken(), info.getId(),signcode);
		delBankModule = new DelBankModule();
		delBankPresistence = new DelBankPresistence(this);
		delBankPresistence.setActitons(delBankAction);
		delBankPresistence.setModule(delBankModule);
		delBankPresistence.execute();
	}

	@Override
	public void handleOkClick() {

		startDelBank();
	}

	@Override
	public void handleDismissClick() {
		// TODO Auto-generated method stub

	}
}
